package org.example.maven.service.Impl;

import com.github.pagehelper.PageHelper;
import jakarta.transaction.Transactional;
import org.example.maven.common.RedisCommon;
import org.example.maven.mapper.classificationMapper;
import org.example.maven.pojo.Classification;
import org.example.maven.pojo.ClassificationSubTree;
import org.example.maven.pojo.ClassificationTree;
import org.example.maven.pojo.classification.ClassificationCategory;
import org.example.maven.pojo.classification.ClassificationCategoryAdd;
import org.example.maven.pojo.classification.ClassificationSubcategoryAdd;
import org.example.maven.pojo.classification.table.*;

import org.example.maven.pojo.eCharts.CategoryStatsDTO;
import org.example.maven.service.ClassificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class classificationServiceImpl implements ClassificationService {
    @Autowired
    private classificationMapper classificationmapper;
    @Autowired
    private RedisCommon redisCommon;
    private final String classification_select="classification_select";
    @Override
    public List<ClassificationTree> getClassification() {
        List<ClassificationTree> cachedList=redisCommon.getList(classification_select);
        if(!cachedList.isEmpty()){
            System.out.println("缓存中找到了");
            return cachedList;
        }
        else {
            //获取所有的分类
            List<Classification> classifications=classificationmapper.getCollectionClassification();
            //获取最后的结果
            List<ClassificationTree> result=new ArrayList<>();
            Map<String,ClassificationTree> map=new HashMap<>();
            Map<String, ClassificationSubTree>map1=new HashMap<>();
            classifications.forEach(node->{
                ClassificationTree classificationTree=new ClassificationTree(
                        node.getCategoryId()+"",
                        node.getCategory()
                );
                ClassificationSubTree classificationTree1=new ClassificationSubTree(
                        node.getSubcategoryId(),
                        node.getSubcategory()
                );
                if(!map.containsKey(node.getCategory())){
                    map.put(node.getCategory(), classificationTree);
                    result.add(classificationTree);
                }
                if(!map.containsKey(node.getSubcategory())){
                    map1.put(node.getSubcategory(), classificationTree1);
                }
            });
            // 3. 构建树形结构
            for (Classification node : classifications) {
                //获取每个节点
                ClassificationTree root = null;
                for(int i=0;i<result.size();i++){
                    if(node.getCategory().equals(result.get(i).getLabel())){
                        root=result.get(i);
                        root.addChild(map1.get(node.getSubcategory()));
                        result.set(i,root);
                    }
                }
            }
            redisCommon.setList(classification_select,result,30, TimeUnit.MINUTES);
            return result;
        }
    }

    @Override
    public Integer getSpecificClassification(String subId) {
        return classificationmapper.getSpecificClassification(subId);
    }

    @Override
    public String getClassificationIdBySubcategory(String subcategory) {
        return classificationmapper.getClassificationIdBySubcategory(subcategory);
    }


    @Override
    public List<ClassificationCategoryList> getClassificationListTableTest(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ClassificationDetail> list = classificationmapper.getClassificationDetail();
        Map<String, ClassificationCategoryList> map1 = new HashMap<>();
        Map<String, List<ClassificationSubcategory>> categorySubcategoriesMap = new HashMap<>();

        for (ClassificationDetail c : list) {
            String category = c.getCategory();
            if (!map1.containsKey(category)) {
                // 创建父分类对象
                ClassificationCategoryList parent = new ClassificationCategoryList();
                parent.setCategory(c.getCategory());
                parent.setCategoryId(c.getCategoryId());
                parent.setSubcategoryNumber(c.getSubcategoryNumber());
                parent.setCategoryIsDeactivate(c.getCategoryIsDeactivate());

                // 初始化当前分类的子列表
                List<ClassificationSubcategory> subcategories = new ArrayList<>();
                parent.setChildren(subcategories);

                map1.put(category, parent);
                categorySubcategoriesMap.put(category, subcategories);
            }

            // 添加子分类到对应的列表
            ClassificationSubcategory sub = new ClassificationSubcategory();
            sub.setSubcategoryId(c.getSubcategoryId());
            sub.setSubcategory(c.getSubCategory());
            sub.setSubcategoryIsDeactivate(c.getSubcategoryIsDeactivate());

            categorySubcategoriesMap.get(category).add(sub);
        }

        return new ArrayList<>(map1.values());
    }

    @Override
    public Integer getClassificationListCount(SearchClassification searchClassification) {
        return classificationmapper.getClassificationListCount(searchClassification);
    }

    @Override
    public List<ClassificationCategoryList> getSpecieClassification(Integer pageNum, Integer pageSize, SearchClassification searchClassification) {
        PageHelper.startPage(pageNum, pageSize);
        List<ClassificationDetail> list = classificationmapper.getSpecieClassification(searchClassification);
        Map<String, ClassificationCategoryList> map1 = new HashMap<>();
        Map<String, List<ClassificationSubcategory>> categorySubcategoriesMap = new HashMap<>();

        for (ClassificationDetail c : list) {
            String category = c.getCategory();
            if (!map1.containsKey(category)) {
                // 创建父分类对象
                ClassificationCategoryList parent = new ClassificationCategoryList();
                parent.setCategory(c.getCategory());
                parent.setCategoryId(c.getCategoryId());
                parent.setSubcategoryNumber(c.getSubcategoryNumber());
                parent.setCategoryIsDeactivate(c.getCategoryIsDeactivate());

                // 初始化当前分类的子列表
                List<ClassificationSubcategory> subcategories = new ArrayList<>();
                parent.setChildren(subcategories);

                map1.put(category, parent);
                categorySubcategoriesMap.put(category, subcategories);
            }

            // 添加子分类到对应的列表
            ClassificationSubcategory sub = new ClassificationSubcategory();
            sub.setSubcategoryId(c.getSubcategoryId());
            sub.setSubcategory(c.getSubCategory());
            sub.setSubcategoryIsDeactivate(c.getSubcategoryIsDeactivate());

            categorySubcategoriesMap.get(category).add(sub);
        }
        return new ArrayList<>(map1.values());
    }

    @Override
    public EditClassification getEditClassification(String id) {
        return classificationmapper.getEditClassification(id);
    }

    @Override
    public void updateClassificationIsDeactivate(String[] id) {
        classificationmapper.updateClassificationIsDeactivate(id);
    }

    @Override
    public void setClassificationIsDeactivate1(String[] id) {
        classificationmapper.setClassificationIsDeactivate1(id);
    }

    @Override
    public void setClassificationSubcategory0(String[] id) {
        classificationmapper.setClassificationSubcategory0(id);
    }

    @Override
    @Transactional
    public void setClassificationSubcategory1(String[] id) {
        List<Integer> list=classificationmapper.getCategoryIsDeactivateBySubcategoryInterval(id);
        int temp=0;
        for(Integer t:list){
            if (t == 0) {
                temp = 1;
                break;
            }
        }
        if(temp==0){
            classificationmapper.setClassificationSubcategory1(id);
        }
    }

    @Override
    public List<Map<String,String>> getClassificationCategory() {
        Map<String,String> map=new HashMap<>();
        List<Map<String,String>> listResult=new ArrayList<>();
        List<ClassificationCategory> list=classificationmapper.getClassificationCategory();
        for(ClassificationCategory c:list){
            if(!map.containsKey(c.getLabel())){
                Map<String,String> tempMap=new HashMap<>();
                map.put(c.getLabel(),c.getValue());
                tempMap.put("label",c.getLabel());
                tempMap.put("value",c.getValue());
                listResult.add(tempMap);
            }
        }
        return listResult;
    }

    @Override
    public void addClassificationCategory(ClassificationCategoryAdd classificationCategoryAdd) {
        classificationmapper.addClassificationCategory(classificationCategoryAdd);
        redisCommon.deleteDataByKey(classification_select);
    }

    @Override
    public void addClassificationSubcategory(ClassificationSubcategoryAdd classificationSubcategoryAdd) {
        classificationmapper.addClassificationSubcategory(classificationSubcategoryAdd);
        redisCommon.deleteDataByKey(classification_select);
    }

    @Override
    public void updateClassificationCategory(EditClassification editClassification) {
        classificationmapper.updateClassificationCategory(editClassification);
        redisCommon.deleteDataByKey(classification_select);
    }

    @Override
    public void updateClassificationSubcategory(EditClassification editClassification) {
        classificationmapper.updateClassificationSubcategory(editClassification);
        redisCommon.deleteDataByKey(classification_select);
    }

    @Override
    public List<CategoryStatsDTO> getCategoryEcharts() {
        return classificationmapper.getCategoryEcharts().stream()
                .sorted((a, b) -> Long.compare(b.getCount(), a.getCount())) // 降序排序
                .limit(10) // 自动处理不足10条的情况
                .collect(Collectors.toList());
    }
}
